﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetEnvironmentVariable
{
    public static class EV
    {
        public static IDictionary GetAll()
        {
            return Environment.GetEnvironmentVariables();
        }

        public static string? GetByKey(string key)
        {
            return Environment.GetEnvironmentVariable(key,EnvironmentVariableTarget.Machine);
        }

        public static bool IsExist(string key)
        {
            return GetByKey(key) != null;
        }

        public static void SetByKey(string key, string value)
        {
            //如果存在，则需要获取到之前的值
            if (IsExist(key))
            {
                string? oldVariable = GetByKey(key);
                List<string> oldVariables = oldVariable.Split(";").ToList();
                List<string> values = value.Split(";").ToList();

                //移除已经存在的
                foreach (var item in values) {
                    oldVariables.Remove(item);
                }

                //重新添加最新的
                foreach (var item in values) {
                    oldVariables.Add(item);
                }

                Environment.SetEnvironmentVariable(key, string.Join(";", oldVariables), EnvironmentVariableTarget.Machine);
            }
            else
            {
                Environment.SetEnvironmentVariable(key, value, EnvironmentVariableTarget.Machine);
            }
        }

    }
}
